<?php

namespace addons\xykeep\listener;

use addons\epay\library\Service;
use app\api\model\xykeep\User;
use app\api\controller\xykeep\Pay;
use app\common\model\StaffOrder as StaffOrderModel;
use app\common\model\Teacher as TeacherModel;
use app\common\model\UserCoupons;
use app\common\model\UserCouponsLog;
use app\common\model\DepositOrder as DepositOrderModel;
use app\common\model\TeacherOrder as TeacherOrderModel;
use think\Config as ThinkConfig;
use think\Db;

/**
 * 订单退款监听
 */
class RefundOrder
{

    public function xykeepJobRefundAll(&$job_id)
    {
        $staffOrder = Db::name('staff_order')->where([
            'job_id' => $job_id,
            'status' => 1,
        ])->select();
        foreach($staffOrder as $k=>$v){
            Db::name('staff_order')->where([
                'id' => $v['id'],
            ])->update([
                'status' => -1,
                'updatetime' => time(),
                'refundtime' => time()
            ]);

            $params['order'] = $v;
            $params['type'] = 'staff';
            \think\Hook::listen('xykeep_order_refund_after', $params);
        }
    }

    public function xykeepOrderRefundAfter(&$params)
    {
        $order = $params['order'];
        $orderType = $params['type'];

        list($orderModel, $order_cn) = Pay::getOrderInstance($orderType);
        if($order['pay_type']=='deposit'){
            if($order['service_type']=='deposit'){
                $order_cn = '接单押金';
            }
            if($order['service_type']=='agency'){
                $order_cn = '接单费用';
            }
            if($order['service_type']=='job'){
                $order_cn = '发布急招';
            }
            if($order['service_type']=='staff'){
                $order_cn = '急招接单';
            }
        }

        if($order['pay_type']=='wechat'){
            $refund=[
                'out_trade_no' => $order['order_sn'],
                'out_refund_no' => time(),
                'total_fee' =>  bcmul((string)$order['pay_fee'],'100'),
                'refund_fee' => bcmul((string)$order['pay_fee'],'100'),
                'refund_desc' => $order_cn.'退款',
                'type' => 'miniapp',
            ];
            $wechat_refund = Service::refunds($refund);
            if($wechat_refund['result_code']!=='SUCCESS'){
                throw new \Exception($wechat_refund['err_code_des']);
            }
        }else{
            //余额支付
            //更新用户余额
            User::money($order['pay_fee'], $order['user_id'], $orderType.'_refund', $order_cn.'退款,订单号:'.$order['order_sn'],$order['id']);
        }

        //减少用户累计消费
        $userInfo = User::where(['id'=>$order['user_id']])->find();
        $after_consume = bcsub((string)$userInfo['xykeep_consume'],(string)$order['pay_fee'],2);
        User::where(['id'=>$order['user_id']])->update(['xykeep_consume'=>$after_consume]);


        if($orderType=='coupons'){
            $userCoupons = new UserCoupons();
            $userCouponsLog = new UserCouponsLog();

            $userCouponsInfo = $userCoupons->where([
                'user_id' => $order['user_id'],
            ])->find();
            if($userCouponsInfo['nums']>=$order['buy_num']){
                $userCoupons->where([
                    'user_id' => $order['user_id'],
                ])->setDec('nums',$order['buy_num']);
                $userCouponsLog->save([
                    'nums' => $order['buy_num'],
                    'price' => $order['total_fee'],
                    'user_id' => $order['user_id'],
                    'type' => 'refund',
                    'order_sn' => $order['order_sn']
                ]);
            }else{
                throw new \Exception('信息券已被使用，不足够退款！');
            }
        }

        if($orderType=='deposit'){
            $depositOrderModel = new DepositOrderModel();
            $depositOrderModel->where([
                'id' => $order['id'],
                'status' => 1
            ])->update(['status'=>-3,'refundtime'=>time()]);

            $teacherOrderModel = new TeacherOrderModel();
            $teacher_order = $teacherOrderModel->where([
                'id' => $order['teacher_order_id'],
            ])->find();
            if($order['service_type']=='deposit'){
                $teacher_order->pay_deposit = 2;
            }else{
                $teacher_order->pay_agency = 2;
            }

            $teacher_order->save();


        }

    }

}